{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from sklearn.datasets import fetch_openml\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "from sklearn.preprocessing import StandardScaler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数据集形状：(1825, 4)\n"
     ]
    }
   ],
   "source": [
    "df=pd.read_csv('BE.csv')\n",
    "print(f\"数据集形状：{df.shape}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   exchange_rate  crude_oil_price\n",
      "0         105.68            39.54\n",
      "1         105.50            39.54\n",
      "2         104.94            41.23\n",
      "3         104.77            42.35\n",
      "4         104.44            42.16\n",
      "0    2431\n",
      "1    2431\n",
      "2    2431\n",
      "3    2431\n",
      "4    2431\n",
      "Name: OT, dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# 数据预处理\n",
    "X=df.drop(columns=['date','OT'],axis=1)\n",
    "print(X.head())\n",
    "y=df['OT']\n",
    "print(y.head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 标准化特征\n",
    "scaler=StandardScaler()\n",
    "X_train_scaled=scaler.fit_transform(X_train)\n",
    "X_test_scaled=scaler.transform(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "均方误差（MSE）：487702.55\n",
      "均方根误差（RMSE）：698.36\n"
     ]
    }
   ],
   "source": [
    "# 线性回归模型\n",
    "lr_model=LinearRegression()\n",
    "lr_model.fit(X_train_scaled,y_train)\n",
    "\n",
    "# 预测\n",
    "y_pred_lr=lr_model.predict(X_test_scaled)\n",
    "mse_lr=mean_squared_error(y_test,y_pred_lr)\n",
    "rmse_lr=np.sqrt(mse_lr)\n",
    "print(f\"均方误差（MSE）：{mse_lr:.2f}\")\n",
    "print(f\"均方根误差（RMSE）：{rmse_lr:.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "===预测示例（第1个测试样本）===\n",
      "实际价格：$2290\n",
      "线性回归预测：$1161\n",
      "特征值：{'exchange_rate': 121.02, 'crude_oil_price': 127.52}\n"
     ]
    }
   ],
   "source": [
    "# 预测示例\n",
    "sample_idx=0\n",
    "sample_features=X_test.iloc[sample_idx:sample_idx+1]\n",
    "sample_actual=y_test.iloc[sample_idx]\n",
    "sample_pred_lr=lr_model.predict(scaler.transform(sample_features))[0]\n",
    "\n",
    "print(f\"\\n===预测示例（第{sample_idx+1}个测试样本）===\")\n",
    "print(f\"实际价格：${sample_actual:.0f}\")\n",
    "print(f\"线性回归预测：${sample_pred_lr:.0f}\")\n",
    "print(f\"特征值：{sample_features.iloc[0].to_dict()}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
